<?php
namespace App\Admin\Controllers\Quality;

use App\Models\Quality\QDictTag;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
class TagController extends AdminController{

    protected $title = '标签管理';

    protected $filters = [
        'type' => null,
        'tag' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['type'] = getOptions(QDictTag::$_type,$this->filters['type']);
        $filtersBlade['tag'] = getOptions(QDictTag::options(),$this->filters['tag']);
        $downloadUrl = '/xqc/quality/tag-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        return view('quality.tag.index', compact('paginator','filtersBlade','action','downloadUrl'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){
        $query = QDictTag::query();
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if(in_array($field,['type','tag'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function destroy($idStr){
        try{
            DB::beginTransaction();
            $qs = QDictTag::query()->whereIn('id',explode(',',$idStr))->get();
            $i = 0;
            foreach ($qs as $q){
                $q->delete();
                $i++;
            }
            DB::commit();
            return response()->json(['status' => true, 'message' => "成功删除{$i}条记录！"]);
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '操作失败！']);
        }
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['类型','标签'];
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="标签.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->orderBy('id','DESC')->chunk(800, function ($re) use ($fp){
                $data = QDictTag::getData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }
}
